package edu.tjut.domain;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.AttributeOverride;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "orders")
public class Order {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	@ManyToOne(optional = false)
	private Customer customer;

	@ManyToOne(optional = false, cascade = CascadeType.ALL)
	private Address shipAddress;

	@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch=FetchType.LAZY)
	@JoinColumn(name = "order_id")
	private Set<OrderLine> orderLines = new HashSet<OrderLine>();

	@Embedded
	@AttributeOverride(name = "amount", column = @Column(name = "order_total"))
	private Money orderTotal = Money.ZERO;
	
	@Enumerated(EnumType.STRING)
	private OrderState state;

	public Order() {
	}

	public Order(Customer customer, Address shipAddress, OrderState state) {
		this.customer = customer;
		this.shipAddress = shipAddress.copy();
		this.state = state;
	}

	public Long getId() {
		return id;
	}

	public void setState(OrderState state) {
		this.state = state;
	}

	public OrderState getState() {
		return state;
	}
	
	public void addOrderLine(OrderLine orderLine) {
		this.orderLines.add(orderLine);
		orderTotal = orderTotal.add(new Money(orderLine.getTotal()));
	}
	
	public void delOrderLine(OrderLine orderLine) {
		this.orderLines.remove(orderLine);
		orderTotal = orderTotal.subtract(new Money(orderLine.getTotal()));
	}

	public Customer getCustomer() {
		return customer;
	}

	public Address getShipAddress() {
		return shipAddress;
	}

	public Set<OrderLine> getOrderLines() {
		return orderLines;
	}

	public Money getOrderTotal() {
		return orderTotal;
	}

	@Override
	public String toString() {
		return "Order [id=" + id + ", customer=" + customer + ", shipAddress=" + shipAddress + ", orderLines=" + orderLines + ", orderTotal=" + orderTotal + ", state=" + state + "]";
	}
}
